﻿
const config = require('../web.config')
const express = require('express')
const path = require('path')
const request = require('request')
const fs = require("pn/fs")
const svg2png = require('svg2png')
const { convert } = require('convert-svg-to-png');

//新建路由
var router = express.Router()
// console.log(config)

var host = 'http://node.aliyin.com'
if (config) {
    host = config.NODE
}

// 生成png准备替换
router.post('/replace',  async(req, res) => {
	let body = req.body,
		list = body.list,
		width = body.width,
		height = body.height,
		ratio = height / width,
		max = 2000;
		if (width > height) {
			if (width > max) {
				width =  max;
				height = width * ratio;
			}
		} else {
			if (height > max) {
				height = max;
				width = height / ratio;
			}
		}
		// console.log(body)
	if (list.length > 1) {
		Promise.all(Array.from(list).map((item, i) => {
			return new Promise(async(resolve, reject) => {
				let buff = await convert(item, {width, height})
				
				fs.writeFile(path.resolve(`./public/png/${body.name + i}.png`), buff)
				resolve(body.name + i)
				
			})
		})).then(arr => {
			arr = arr.join('_')
			res.send({obj: body.obj, mtl:`${host}/mtl?name=${arr}&mtl=${body.mtl}`})
		})
	} else {
		let buff = await convert(list[0], {width, height})
	
		fs.writeFile(path.resolve(`./public/png/${body.name}1.png`), buff)
		res.send({obj: body.obj, mtl:`${host}/mtl?name=${body.name}1&mtl=${body.mtl}`})
		
	}
})
router.get('/mtl', (req, res) => {
	let name = req.query.name,
		file = req.query.fileName || 'reticule',
		mtl = req.query.mtl;
		if (mtl.lastIndexOf('.mtl') > 0) {
			 //console.log(file,mtl,name)//'http:' + 
			let arr = name.split('_');
			request(mtl, (err, response, data) => {
				// console.log(arr)
				data = data.replace(/server/g, 'service')
				arr.forEach((item, i) => {
					let src = `${host}/png/${item}.png?v=${new Date().getTime()}`;
					let reg = new RegExp(`replace${i}.(png|jpg)`, 'g')
					data = data.replace(reg, src)
				})
				res.send(data)
			})
		}
})

















module.exports = router;